package org.jeecg.tender.taskJob;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.readExcel.entity.TenderInformationKeywordManagementRelEntity;
import org.jeecg.readExcel.service.TenderInformationKeywordManagementRelService;
import org.jeecg.tender.config.WebDriverConfig;
import org.jeecg.tender.information.entity.TenderInformation;
import org.jeecg.tender.information.service.ITenderInformationService;
import org.jeecg.tender.keyword.entity.TenderSecurityKeywordManagement;
import org.jeecg.tender.keyword.service.ITenderSecurityKeywordManagementService;
import org.jeecg.tender.project.dto.req.SendProjectNoticeReqDto;
import org.jeecg.tender.project.dto.util.SendProjectNoticeUtil;
import org.jeecg.tender.project.service.ITenderProjectNoticeService;
import org.jeecg.tender.website.entity.TenderWebsiteManagement;
import org.jeecg.tender.website.service.ITenderWebsiteManagementService;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class DigitalgdTaskJob implements Job {

    @Resource
    private ITenderInformationService tenderInformationService;

    @Resource
    private TenderInformationKeywordManagementRelService tenderInformationKeywordManagementRelService;

    @Resource
    private ITenderSecurityKeywordManagementService tenderSecurityKeywordManagementService;

    @Resource
    private ITenderWebsiteManagementService websiteManagementService;

    @Resource
    private WebDriverConfig webDriverConfig;

    @Resource
    private ITenderProjectNoticeService tenderProjectNoticeService;

    private String baseUrl = "https://www.digitalgd.com.cn/cooperation/notice/purchase/page/";

    /**
     * 数字广东爬虫任务
     * @param context
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 启动 Firefox 浏览器
        WebDriver driver = webDriverConfig.driver();
        List<SendProjectNoticeReqDto> noticeInfoList = new ArrayList<>();
        try {
            //更新招标网站爬取状态
            websiteManagementService.lambdaUpdate().eq(TenderWebsiteManagement::getWebsiteName,"数字广东网站")
                    .set(TenderWebsiteManagement::getCrawlStatus, 1).update();

            List<TenderSecurityKeywordManagement> list = tenderSecurityKeywordManagementService.lambdaQuery().list();
            // 假设使用 entity 的某个唯一字段（例如 id 或 keyword 作为 key）
            Map<String, TenderSecurityKeywordManagement> keywordManagMap = list.stream()
                    .collect(Collectors.toMap(
                            TenderSecurityKeywordManagement::getKeywordName,  // key
                            entity -> entity, // value
                            (existing, replacement) -> existing // 发生重复时保留原值
                    ));


            // 循环翻页并抓取内容
            for (int page = 1; page <= 200; page++) { // 设置抓取的页数为 5
                String url = baseUrl + page + "/"; // 动态生成每一页的 URL
                driver.get(url); // 访问目标网站
                log.info("抓取第{}页的数据，地址为：{}",page, url);


                // 获取所有 tender 链接
                List<WebElement> tenderLinks = driver.findElements(By.cssSelector("div.news-list a"));
                List<TenderInformationKeywordManagementRelEntity> managementRelEntities = new ArrayList<>();
                List<String> detailUrls = new ArrayList<>();
                for (WebElement link : tenderLinks) {
                    String tenderUrl = link.getAttribute("href"); // 获取每个链接的 href 属性值，即详情页的链接
                    detailUrls.add(tenderUrl);
                }

                //获取链接
                for (String detailUrl : detailUrls) {
                    driver.get(detailUrl);
                    // 获取 tender 信息
                    WebElement timeElement = driver.findElement(By.cssSelector(".news-info"));
                    WebElement titleElementdesc = driver.findElement(By.cssSelector(".news-title"));
                    WebElement elementdetail = driver.findElement(By.cssSelector(".news-detail"));
                    String timeStr = timeElement.getText();
                    String title = titleElementdesc.getText(); // 提取招标标题
                    String detailTitle = elementdetail.getText();
                    log.info("招标标题: " + title);
                    log.info("招标详情: " + detailTitle);

                    // 检查是否需要过滤
                    if (webDriverConfig.checkFilterTitle(title)) {
                        log.info("招标标题包含过滤关键词，跳过当前公告。");
                        continue;
                    }

                    TenderSecurityKeywordManagement keywordManagement = keywordManagMap.entrySet().stream()
                            .filter(entry -> title.contains(entry.getKey())) // 模糊匹配
                            .map(Map.Entry::getValue) // 提取 value
                            .findFirst() // 取第一个匹配的值
                            .orElse(null); // 如果找不到，则返回 null

                    if (null == keywordManagement) {
                        log.info("未找到匹配的关键词，跳过当前公告。");
                        continue; // 跳过当前循环，继续下一次循环
                    }

                    Long count = tenderInformationService.lambdaQuery().eq(TenderInformation::getTenderTitle, title).count();
                    if (count > 0) {
                        log.info("该招标信息已存在，跳过当前公告。");
                        continue; // 跳过当前循环，继续下一次循环
                    }


                    // 使用正则表达式提取各个字段
                    TenderInformation tenderInformation = new TenderInformation();
                    extractFields(timeStr,title,detailTitle, tenderInformation, "数字广东网站");
                    tenderInformationService.save(tenderInformation);

                    TenderInformationKeywordManagementRelEntity relEntity = new TenderInformationKeywordManagementRelEntity();
                    relEntity.setInformation_id(String.valueOf(tenderInformation.getId()));
                    relEntity.setSecurity_keyword_management_id(String.valueOf(keywordManagement.getId()));
                    relEntity.setCreate_by("system");
                    relEntity.setCreate_time(new Date());
                    managementRelEntities.add(relEntity);
                    SendProjectNoticeReqDto sendProjectNoticeReqDto = SendProjectNoticeUtil.buildSendProjectNoticeReqDto(keywordManagement.getId(), tenderInformation);
                    sendProjectNoticeReqDto.setKeywordName(keywordManagement.getKeywordName());
                    sendProjectNoticeReqDto.setAddress(detailUrl);
                    noticeInfoList.add(sendProjectNoticeReqDto);
                }

                // 批量保存数据
                tenderInformationKeywordManagementRelService.saveBatch(managementRelEntities);

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭浏览器
            driver.quit();
            //更新招标网站爬取状态
            websiteManagementService.lambdaUpdate().eq(TenderWebsiteManagement::getWebsiteName,"数字广东网站")
                    .set(TenderWebsiteManagement::getCrawlStatus, 0).update();
            // 发送通知
            tenderProjectNoticeService.sendTenderProjectNotice(noticeInfoList);
        }
    }

    private static void extractFields(String timeStr, String title, String detailTitle, TenderInformation tenderInformation, String websiteName) {
        log.info("没有匹配到字段.给默认值");
        tenderInformation.setBiddingUnit("--");  // 设置招标单位为“--”
        tenderInformation.setBiddingUnitIndustry("--");  // 设置招标单位行业为“--”
        tenderInformation.setTenderAmount(0.0);  // 设置招标金额为 0.0
        tenderInformation.setBiddingNum("--");
        tenderInformation.setTenderType("--");
        tenderInformation.setStartTime(null);
        tenderInformation.setEndTime(null);
        // 假设这是你的时间字符串
        String time = "2025-02-24 15:30:00";
        // 创建日期格式对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 将String转为Date
            Date date = sdf.parse(timeStr);
            tenderInformation.setTenderDate(date);
            System.out.println("转换后的Date对象: " + date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tenderInformation.setBiddingWinner("--");  // 设置中标单位为“--”
        tenderInformation.setAgency("--");  // 设置代理机构为“--”
        tenderInformation.setTenderTitle(title);
        tenderInformation.setTenderDesc(detailTitle);
        tenderInformation.setTenderDescType("txt");
        tenderInformation.setWebsiteName(websiteName);
        tenderInformation.setCrawlTime(new Date());  // 设置爬取时间为当前时间
        tenderInformation.setCreateBy("system");
        tenderInformation.setCreateTime(new Date());
        tenderInformation.setUpdateBy("system");
        tenderInformation.setUpdateTime(new Date());
    }
}
